﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

namespace NinjaToolbox
{
    public class SphereShape : PhysicsObjectShapeBase
    {
        public Vector3 center;
        public float radius = 1f;


        public override bool IsHit(Vector3 compareMassPoint)
        {
            return Vector3.Distance(GetWorldPosition(), compareMassPoint) <= radius;
        }

        public override bool IsHit(PhysicsObjectShapeBase shape, out Vector3 referencePoint)
        {
            if (shape is CapsuleShape)
            {
                return PhysicsUtil.CapsuleHitOther(shape as CapsuleShape, this, out referencePoint);
            }
            else
            {
                var edgePoint = shape.MassPointToEdge(shape.GetWorldPosition(), GetWorldPosition());
                referencePoint = edgePoint;
                return IsHit(edgePoint);
            }
        }

        public override Vector3 MassPointToEdge(Vector3 massPoint, Vector3 outsidePoint)
        {
            return massPoint + (outsidePoint - massPoint).normalized * radius;
        }

        public override Vector3 GetWorldPosition()
        {
            return transform.localToWorldMatrix.MultiplyPoint3x4(center);
        }

        protected override void DrawGizmos()
        {
            var cacheColor = Gizmos.color;

            Gizmos.color = Color.Lerp(Color.green, Color.gray, 0.5f);

            Gizmos.DrawWireSphere(GetWorldPosition(), radius);

            Gizmos.color = cacheColor;
        }
    }
}
